import createAxiosError from 'axios/lib/core/createError'
import LeUtils from './le-utils'
import Axios,{leAxiosInterceptorsRequestError} from './axios'
import LeStorage from './le-storage'
import url from 'url';

function sessionIsChanged(){
    let cacheSessionId = LeStorage.localGet("routeCacheId")
    let currentSessionId = window.LeServiceRouteCacheId
    if(currentSessionId != cacheSessionId ){
        LeStorage.localSet("routeCacheId",currentSessionId)
        return true
    }
    return false
}

const LeRoute = {
    _inited:false,
    _quiet:false,
    _loadingService:null,
    async initCache(){
        if(sessionIsChanged()){
            LeStorage.clearLeServiceRoutes()
            this._inited = false
        }
        if(this._inited){
            return
        }
        let _this = this;
        if(!LeUtils.typeIs('undefined',window.LeServiceRoutes)){
            LeStorage.setLeServiceRoutes(LeUtils.valueGet(window, 'LeServiceRoutes',{}))
            _this._inited = true;
            return
        }
        let LeServiceRoutesApi = LeUtils.valueGet(window, 'LeServiceRoutesApi', false);
        if( !! LeServiceRoutesApi){
            await Axios.quiet().get(LeServiceRoutesApi).then(function (res) {
                LeStorage.setLeServiceRoutes(LeUtils.valueGet(res, 'data',{}))
                _this._inited = true;
            });
        }

    },
    get(routeName) {
        let _this = this

        _this.initCache()

        if ( !LeUtils.typeIs('string', routeName)
            || LeUtils.isEmpty(routeName)
        ) {
            return null
        }
        let leServiceRoutes = LeStorage.getLeServiceRoutes()

        let route = {}

        if(routeName.indexOf('/') != -1){
            route =  {
                uri: routeName,
                method: "GET"
            }
        }else if(routeName in leServiceRoutes){
            route =  leServiceRoutes[routeName]
        }else if ( !!LeServiceRouteApi ) {

            window.jQuery.ajax({
                url:LeServiceRouteApi,
                dataType:"json",
                method:"get",
                data:{
                    name:routeName
                },
                async:false,
                success:function (res){
                    route = LeUtils.valueGet(res, 'data',{})
                    LeStorage.setLeServiceRoute(routeName,route)
                }
            })


        }

        if(!route || !LeUtils.typeIs('object', route)){
            route = {}
        }

        route.request = function (params, headers) {
            _this.request(_this,params, headers)
        }
        return route;
    },
    _axios:Axios,
    quiet(){
        let _this = Object.assign({},this);
        _this._quiet = true
        _this._axios = Axios.quiet()
        return _this
    },
    useLoading(loadingService){
        let _this = Object.assign({},this);
        _this._loadingService = loadingService;
        _this._axios = _this._axios.useLoading(loadingService);
        return _this
    },
    buildUrlAndMethod(api,params){
        params = Object.assign({}, params)
        let route = null;
        if (LeUtils.typeIs('object', api)) {
            route = api;
        } else if (LeUtils.typeIs('string', api)) {
            route = this.get(api);
        }
        let uri = LeUtils.valueGet(route, 'uri')
        let method = LeUtils.valueGet(route, 'method', 'GET')
        if (!LeUtils.typeIs('string', method)) {
            method = 'GET'
        }

        if(uri){
            let paraReg = new RegExp(/\{(.*?)\}/, 'g');
            uri = uri.replace(paraReg, function (para, paraKey) {
                paraKey = paraKey.trim('?')
                //debugger
                let value = LeUtils.valueGet(params, paraKey, '');
                //delete data[paraKey];
                return value;
            });
        }

        return {uri,method}

    },
    buildUrl(api,params){
        let {uri,method} = this.buildUrlAndMethod(api,params);
        if (!uri) {
            return ""
        }
        let _url = url.parse(uri)
        _url.query = params
        return _url.format();

    },
    request(api, params, headers) {
        let _this = this;
        try {
            let data = Object.assign({}, params)
            let {uri,method} = this.buildUrlAndMethod(api,params);
            if (!uri) {
                throw new Error('路由错误')
            }

            let use_params = true;


            if (['PUT', 'POST', 'PATCH'].includes(method.toUpperCase())) {
                use_params = false;
            }

            //console.log(uri,data, headers,method)
            //console.log(uri);


            return this._axios.request({
                url: uri,
                method: method,
                params: use_params ? data : null,
                data: use_params ? null : data,
                headers: headers,
            })

        }catch (e) {

            try {
                if(_this._loadingService) {
                    _this._loadingService.close();
                }
            }catch (e) {

            }
            return leAxiosInterceptorsRequestError(createAxiosError(
                '接口错误 ' + e.message,
                null,
                null,
                null,
                null,
            ),this._quiet);
        }
    },
    go(api,params,openNew){
        let uri = this.buildUrl(api,params);
        if (!uri) {
            throw new Error('路由错误')
        }
        if(true === openNew){
            window.open(uri,"_blank")
            return
        }
        window.location.href = uri;
    },
}


export default LeRoute
